﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using Eqwww.Data;
using Eqwww.Domain.Models.SystemManage;
using Eqwww.App.SystemManage;
using Eqwww.Code;
using Eqwww.App.Authorize;
using Eqwww.App.Identity;

namespace Eqwww.Web.Areas.SystemManage.Controllers
{
    [Area("SystemManage")]
    public class StrategoryController : ControllerBase
    {
        private StrategoryApp _strategoryApp;
        private AuthorizeApp _authorizeApp;
        private RoleApp _roleApp;

        public StrategoryController(StrategoryApp strategoryApp, AuthorizeApp authorizeApp, RoleApp roleApp)
        {
            _strategoryApp = strategoryApp;
            _authorizeApp = authorizeApp;
            _roleApp = roleApp;
        }

        [AuthFilter]
        // GET: SystemManage/Strategory
        public IActionResult Index()
        {
            var currentModuleCode = "SystemManage_Strategory";
            ViewData["SelectedButtons"] = _authorizeApp.GetAuthorizedModuleButtons(User, currentModuleCode, ModuleButtonPosition.Selected);
            ViewData["InitialButtons"] = _authorizeApp.GetAuthorizedModuleButtons(User, currentModuleCode, ModuleButtonPosition.Initial);

            return View();
        }

        [AuthFilter]
        // GET: SystemManage/Strategory/Details/5
        public IActionResult Details(string id)
        {
            if (id == null)
            {
                return NotFoundObject();
            }
            var model = _strategoryApp.Get(id, true);
            if (model == null)
                return NotFoundObject();

            ViewData["RelatedRoles"] = _strategoryApp.GetRolesByStrategoryId(model.Id);
            ViewData["Items"] = _authorizeApp.GetAuthorizedModuleAndButtonTreeCollapseToggleListByStrategoryId(id);
            return View(model);
        }

        [AuthFilter]
        public IActionResult Create()
        {
            return View();
        }

        [HttpPost]
        [ExceptionFilter]
        [ValidateAntiForgeryToken]
        public IActionResult Create([Bind("Id,Code,Name,SortCode,IsSystem,IsSuper,Description")] StrategoryModel model)
        {
            if (ModelState.IsValid)
            {
                return Json(_strategoryApp.Create(model));
                
            }
            return Json(Common.ModelStateErrorResult(ModelState));
        }

        [AuthFilter]
        public IActionResult Edit(string id)
        {
            if (id == null)
            {
                return NotFoundObject();
            }
            var model = _strategoryApp.Get(id);
            if (model == null)
            {
                return NotFoundObject();
            }
            if (model.IsSystem == true)
                return ErrorView("系统策略不允许修改");
            return View(model);
        }

        
        [HttpPost]
        [ExceptionFilter]
        [ValidateAntiForgeryToken]
        public IActionResult Edit(string id, [Bind("Id,Code,Name,SortCode,IsSystem,IsSuper,Description")] StrategoryModel model)
        {
            if (id != model.Id)
            {
                return Error("GET ID和POST ID 不一致");
            }

            if (ModelState.IsValid)
            {
                var existModel = _strategoryApp.Get(id);
                if (existModel == null)
                    return Error("未查询到指定实体");
                if (existModel.IsSystem == true)
                    return Error("系统策略不允许修改");
                return Json(_strategoryApp.Update(model));
                
            }
            return Json(Common.ModelStateErrorResult(ModelState));
        }

        
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public IActionResult DeleteConfirmed(string id)
        {
            return Json(_strategoryApp.Remove(id));
        }

        
        [AuthFilter]
        public IActionResult ModuleRelation(string id)
        {
            var model = _strategoryApp.Get(id);
            if (model.IsSystem == true)
                return ErrorView("系统策略不允许修改");
            if (model.IsSuper == true)
                return ErrorView("超管策略不允许修改");

            ViewData["Items"] = _authorizeApp.GetAuthorizedModuleAndButtonTreeCollapseToggleListByStrategoryId(id);
            return View();
        }

        [HttpPost, ActionName("ModuleRelation")]
        [ExceptionFilter]
        [ValidateAntiForgeryToken]
        public IActionResult ModuleRelationConfirmed(string strategoryId, string permissions)
        {
            var ps = string.IsNullOrEmpty(permissions) ? new string[] { } : permissions.Split(',');
            return Json(_strategoryApp.UpdatePermissions(strategoryId, ps));
        }

        [AuthFilter]
        public IActionResult RoleRelation(string id)
        {
            var model = _strategoryApp.Get(id);
            if (model.IsSystem == true)
                return ErrorView("系统策略不允许修改");
            if (model.IsSuper == true)
                return ErrorView("超管策略不允许修改");

            var relatedRoles = from p in _strategoryApp.GetRolesByStrategoryId(model.Id).ToList() select p.Id;

            var roles = from p in _roleApp.Roles.AsNoTracking().Where(x => x.DeleteMark != true).OrderBy(x => x.SortCode).ToList()
                        select new TreeCollapseToggleModel
                        {
                            Id = p.Id,
                            Text = p.ShowName??p.Name,
                            Url = p.Description,
                            ParentId = null,
                            SortCode = p.SortCode,
                            Icon = "people",
                            CanToggle = true,
                            ToggleMark = relatedRoles.Contains(p.Id),
                            Expend = true,
                            Disabled = false
                        };

            ViewData["DataItems"] = roles.ToList();
            return View();
        }

        [HttpPost]
        [ExceptionFilter]
        [ValidateAntiForgeryToken]
        public IActionResult RoleRelationSubmit(string strategoryId, string roles)
        {
            var ps = string.IsNullOrEmpty(roles) ? new string[] { } : roles.Split(',');
            return Json(_strategoryApp.UpdateRelatedRolesByStrategoryId(strategoryId, ps));
        }

        public IActionResult GridJson(string keyword, Pagination pagination)
        {
            var data = new
            {
                rows = _strategoryApp.GetPagedList(keyword,pagination),
                total = pagination.total,
                page = pagination.page,
                records = pagination.records
            };
            return Content(data.ToJson());
        }

        [HttpPost]
        [ExceptionFilter]
        [ValidateAntiForgeryToken]
        public IActionResult UpdateIsSystem(string id)
        {
            return Json(_strategoryApp.UpdateIsSystem(id, true));
        }

        [HttpPost]
        [ExceptionFilter]
        [ValidateAntiForgeryToken]
        public IActionResult UpdateIsNotSystem(string id)
        {
            return Json(_strategoryApp.UpdateIsSystem(id, false));
        }
    }
}
